<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\TrainTypeModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Systemtype extends AuthController
{
    public function list(Request $request)
    {
        $page = input('page', 1);
        $limit = input('size', 10);
        $name = input('name', '');
        $type = input('type', '');
        $data = \app\model\type\SystemType::where('status', 1)
            ->when($name, function ($query) use ($name) {
                $query->where('name', 'like', "%{$name}%");
            })
            ->when($type, function ($query) use ($type) {
                $query->where('type', $type);
            })
            ->paginate($limit);

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
        ]);
    }

    public function info(Request $request)
    {
        $id = input('id', '');
        if ($id) {
            $data = \app\model\type\SystemType::getOne($id);
        } else {
            $data = null;
        }
        return app('json')->success([
            'data' => $data
        ]);
    }

    public function save(Request $request)
    {
        $param = $request->only([
            'name', 'type'
        ]);
        try {
            validate([
                'name|名称' => 'require|max:50',
                'type|分类' => 'require|in:1,2',
            ])->check($param);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        $id = input('id', '');
        if ($id) {
            $res = \app\model\type\SystemType::update($param, ['id' => $id]);
        } else {
            $res = \app\model\type\SystemType::create($param);
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        \app\model\type\SystemType::dataDelete($id);
        return app('json')->success();
    }
}